/**
 * SEO分析面板组件
 * 显示关键词分析、SEO评分、优化建议
 */

import React from 'react';
import { Card, Tag, Progress, List, Row, Col, Statistic, Table, Space, Tooltip } from 'antd';
import {
  KeyOutlined,
  TrophyOutlined,
  FileTextOutlined,
  LinkOutlined,
  PictureOutlined,
  BulbOutlined,
} from '@ant-design/icons';
import type { SEOAnalysis, Keyword } from '@/stores/optimizer.store';
import './style.css';

interface SEOPanelProps {
  analysis: SEOAnalysis;
  onApplyKeyword?: (keyword: string) => void;
}

/**
 * 获取关键词密度颜色
 */
const getDensityColor = (density: number): string => {
  if (density > 3) return 'red';        // 过高
  if (density >= 1 && density <= 3) return 'green';  // 适中
  return 'default';                      // 过低
};

/**
 * 获取重要性标签
 */
const getImportanceTag = (importance: Keyword['importance']) => {
  const tagMap = {
    primary: { text: '核心', color: 'red' },
    secondary: { text: '次要', color: 'orange' },
    tertiary: { text: '辅助', color: 'blue' },
  };

  const { text, color } = tagMap[importance];
  return <Tag color={color}>{text}</Tag>;
};

export const SEOPanel: React.FC<SEOPanelProps> = ({ analysis, onApplyKeyword }) => {
  // 关键词表格列定义
  const keywordColumns = [
    {
      title: '关键词',
      dataIndex: 'word',
      key: 'word',
      render: (text: string, record: Keyword) => (
        <Space>
          {getImportanceTag(record.importance)}
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '出现次数',
      dataIndex: 'count',
      key: 'count',
      width: 100,
      sorter: (a: Keyword, b: Keyword) => a.count - b.count,
    },
    {
      title: '密度',
      dataIndex: 'density',
      key: 'density',
      width: 120,
      render: (density: number) => (
        <Tag color={getDensityColor(density)}>
          {density.toFixed(2)}%
        </Tag>
      ),
      sorter: (a: Keyword, b: Keyword) => a.density - b.density,
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_: any, record: Keyword) => (
        onApplyKeyword && (
          <a onClick={() => onApplyKeyword(record.word)}>优化</a>
        )
      ),
    },
  ];

  return (
    <div className="seo-panel">
      {/* 整体SEO评分 */}
      <Row gutter={16}>
        <Col span={8}>
          <Card>
            <Statistic
              title="标题SEO评分"
              value={analysis.titleScore}
              suffix="/ 100"
              valueStyle={{ color: analysis.titleScore >= 70 ? '#3f8600' : '#cf1322' }}
              prefix={<TrophyOutlined />}
            />
            <div style={{ marginTop: 8, fontSize: 12, color: '#8c8c8c' }}>
              标题长度: {analysis.titleLength} 字符
            </div>
          </Card>
        </Col>

        <Col span={8}>
          <Card>
            <Statistic
              title="Meta描述评分"
              value={analysis.metaDescriptionScore}
              suffix="/ 100"
              valueStyle={{ color: analysis.metaDescriptionScore >= 70 ? '#3f8600' : '#cf1322' }}
              prefix={<FileTextOutlined />}
            />
          </Card>
        </Col>

        <Col span={8}>
          <Card>
            <Statistic
              title="关键词数量"
              value={analysis.keywords.length}
              prefix={<KeyOutlined />}
            />
          </Card>
        </Col>
      </Row>

      {/* 关键词分析 */}
      <Card
        title={
          <Space>
            <KeyOutlined />
            <span>关键词分析</span>
          </Space>
        }
        size="small"
        style={{ marginTop: 16 }}
      >
        <Table
          dataSource={analysis.keywords.slice(0, 10)}
          columns={keywordColumns}
          rowKey="word"
          size="small"
          pagination={false}
        />

        {analysis.keywords.length > 10 && (
          <div style={{ marginTop: 12, textAlign: 'center', color: '#8c8c8c' }}>
            仅显示前10个关键词
          </div>
        )}
      </Card>

      {/* 关键词分布 */}
      <Card title="关键词分布" size="small" style={{ marginTop: 16 }}>
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="标题"
              value={analysis.keywordDistribution.title}
              suffix="次"
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="首段"
              value={analysis.keywordDistribution.firstParagraph}
              suffix="次"
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="正文"
              value={analysis.keywordDistribution.body}
              suffix="次"
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="末段"
              value={analysis.keywordDistribution.lastParagraph}
              suffix="次"
            />
          </Col>
        </Row>
      </Card>

      {/* 标题优化建议 */}
      {analysis.titleSuggestion && (
        <Card title="标题优化建议" size="small" style={{ marginTop: 16 }}>
          <div className="title-suggestion">
            <BulbOutlined style={{ color: '#1890ff', marginRight: 8 }} />
            {analysis.titleSuggestion}
          </div>
        </Card>
      )}

      {/* Meta描述 */}
      {analysis.metaDescription && (
        <Card title="Meta描述" size="small" style={{ marginTop: 16 }}>
          <p className="meta-description">{analysis.metaDescription}</p>
          <Progress
            percent={Math.min(100, (analysis.metaDescription.length / 160) * 100)}
            strokeColor={
              analysis.metaDescription.length >= 150 && analysis.metaDescription.length <= 160
                ? '#52c41a'
                : '#faad14'
            }
            format={(percent) => `${analysis.metaDescription?.length || 0}/160 字符`}
          />
        </Card>
      )}

      {/* 标题结构 */}
      {analysis.headingStructure.length > 0 && (
        <Card title="标题结构" size="small" style={{ marginTop: 16 }}>
          <List
            size="small"
            dataSource={analysis.headingStructure}
            renderItem={(item) => (
              <List.Item>
                <Space>
                  <Tag color="blue">{item.level}</Tag>
                  <span>{item.text}</span>
                  <span style={{ color: '#8c8c8c', fontSize: 12 }}>
                    (位置: {item.position})
                  </span>
                </Space>
              </List.Item>
            )}
          />
        </Card>
      )}

      {/* 链接和图片统计 */}
      <Card title="链接与图片" size="small" style={{ marginTop: 16 }}>
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="内部链接"
              value={analysis.internalLinks}
              prefix={<LinkOutlined />}
              valueStyle={{ fontSize: 20 }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="外部链接"
              value={analysis.externalLinks}
              prefix={<LinkOutlined />}
              valueStyle={{ fontSize: 20 }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="图片总数"
              value={analysis.imageCount}
              prefix={<PictureOutlined />}
              valueStyle={{ fontSize: 20 }}
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="有Alt文本"
              value={analysis.imagesWithAlt}
              prefix={<PictureOutlined />}
              valueStyle={{ fontSize: 20, color: analysis.imagesWithAlt === analysis.imageCount ? '#52c41a' : '#faad14' }}
            />
          </Col>
        </Row>
      </Card>

      {/* SEO优化建议 */}
      <Card title="SEO优化建议" size="small" style={{ marginTop: 16 }}>
        <List
          size="small"
          dataSource={analysis.recommendations}
          renderItem={(item, index) => (
            <List.Item>
              <Space>
                <span className="recommendation-number">{index + 1}.</span>
                <span>{item}</span>
              </Space>
            </List.Item>
          )}
        />
      </Card>

      {/* 关键词建议 */}
      <Row gutter={16} style={{ marginTop: 16 }}>
        {analysis.competitorKeywords.length > 0 && (
          <Col span={12}>
            <Card title="竞争关键词" size="small">
              <div className="keyword-tags">
                {analysis.competitorKeywords.map((kw) => (
                  <Tag key={kw} color="orange" style={{ marginBottom: 8 }}>
                    {kw}
                  </Tag>
                ))}
              </div>
            </Card>
          </Col>
        )}

        {analysis.longTailKeywords.length > 0 && (
          <Col span={12}>
            <Card title="长尾关键词建议" size="small">
              <div className="keyword-tags">
                {analysis.longTailKeywords.map((kw) => (
                  <Tag key={kw} color="purple" style={{ marginBottom: 8 }}>
                    {kw}
                  </Tag>
                ))}
              </div>
            </Card>
          </Col>
        )}
      </Row>
    </div>
  );
};
